<template>
  <div class="params">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-alert
        title="注意！只允许为三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 级联选择器 -->
      <el-row class="cate_opt">
        <el-col>
          <span>选择商品分类 :</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            class="red_btn"
            size="mini"
            :disabled="idBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染tag标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClosed(index, scope.row)"
                  >{{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  class="green_btn"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  class="red_btn"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            class="red_btn"
            size="mini"
            :disabled="idBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染tag标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClosed(index, scope.row)"
                  >{{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  class="green_btn"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  class="red_btn"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加参数或者属性的对话框 -->
      <el-dialog
        :title="'添加' + addTitle"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed"
      >
        <!-- 添加参数或者属性的表单区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item :label="addTitle" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改动态参数或静态属性对话框 -->
      <el-dialog
        :title="'修改' + addTitle"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="editDialogClosed"
      >
        <!-- 修改参数或者属性的表单区域 -->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item :label="addTitle" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "params",
  data() {
    return {
      // *商品分类列表
      cateList: [],
      // *级联选择器的配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true, //*控制可以选中一级选项
      },
      // *级联选择器的双向绑定选中的id的数组
      selectedCateKeys: [],
      // *页签区
      activeName: "many",
      //*动态参数表格数据
      manyTableData: [],
      //*静态属性表格数据
      onlyTableData: [],
      // *控制添加属性或分类的对话框
      addDialogVisible: false,
      // *添加参数或属性的表单数据
      addForm: {
        attr_name: "",
      },
      // *添加参数或属性的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // *控制修改属性或分类的对话框
      editDialogVisible: false,
      // *修改参数或属性的表单数据
      editForm: {},
      // *修改参数或属性的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // *控制输入文本框的显示
      inputVisible: false,
      // *文本框的值双向绑定
      inputValue: "",
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // *获取分类列表数据请求
    async getCateList() {
      const res = await this.$http.get("categories");
      if (res.data.meta.status !== 200) {
        return this.$message.error("获取分类失败！");
      }
      this.cateList = res.data.data;
    },
    // *级联选择框选中的发生变化 会触发此函数
    handleChange() {
      this.getParamsList();
    },
    //*tab页签单击事件的处理函数
    handleTabClick() {
      this.getParamsList();
    },
    //a获取参数列表
    async getParamsList() {
      //如果选中的数组长度不等于3 表示选中的不是3级分类 清空数组
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      // *如果选中的是三级分类 根据三级分类的id发起请求 获取参数
      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName },
      });
      // *遍历所有的data数据 把attr_vals从字符串变成数组
      res.data.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // *给每一行数据保存一个自己的inputVisible和inputValue
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data.data;
      } else {
        this.onlyTableData = res.data.data;
      }
    },
    //a监听添加参数或者属性的对话框关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //a 确定按钮提交添加参数或属性请求
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const res = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        );
        if (res.data.meta.status !== 201) {
          return this.$message.error("添加失败！");
        }
        this.$message.success("添加成功！");
        this.addDialogVisible = false;
        this.getParamsList();
      });
    },
    //a 单击编辑按钮 查询角色信息的事件
    async showEditDialog(id) {
      this.editDialogVisible = true;
      // *根据id查询用户信息
      const res = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.data.meta.status !== 200) {
        return this.$message.error("查询信息失败！");
      }
      this.editForm = res.data.data;
    },
    //a修改对话框关闭的回调事件 重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //a 确定按钮提交修改表单的事件
    editParams() {
      // 先检验值是否合理
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请检验信息是否填写完整！");
        }
        const res = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.data.meta.status !== 200) {
          return this.$message.error("修改信息失败！");
        }
        this.$message.success("修改信息成功！");
        this.getParamsList();
        this.editDialogVisible = false;
      });
    },
    // a单击删除按钮删除信息
    async removeParams(id) {
      const removeRole = await this.$confirm(
        "此操作将永久删除该属性, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erro) => erro);
      if (removeRole !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // a 发起删除属性请求
      const res = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.data.meta.status !== 200) {
        this.$message.error("删除属性失败!");
      }
      this.$message.success("已成功删除该属性！"); //* 提示删除成功
      this.getParamsList(); //*更新分类列表
    },
    //a 文本框失去了焦点或enter按下都会触发
    handleInputConfirm(row) {
      // .trim()把字符串两端的空格去掉
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果输入的内容不为空 需要做下面的处理
      // *把新输入的值push进存放参数的数组里
      row.attr_vals.push(row.inputValue.trim());
      // *发起请求传给后台
      this.saveAttrValues(row);
    },
    // *处理数组的请求
    async saveAttrValues(row) {
      const res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.data.meta.status !== 200) {
        return this.$message.error("修改参数失败！");
      }
      this.$message.success("修改参数成功！");
      row.inputValue = "";
      row.inputVisible = false;
    },
    // *当
    handleClosed(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrValues(row);
    },
    //*点击按钮展示输入文本框
    showInput(row) {
      row.inputVisible = true;
      // todo $nextTick方法是当页面上的元素被重新渲染后 再执行回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  computed: {
    // *如果未显示三级分类 禁用按钮
    idBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // *当前选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]; //return的是三级分类的id
      }
      return null;
    },
    // *添加参数/属性对话框的title
    addTitle() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style scoped lang="less">
.el-alert {
  width: 400px;
  padding: 10px 15px;
}
.cate_opt {
  margin: 20px 0;
  span {
    color: rgb(75, 75, 75);
    margin-right: 20px;
  }
}
.el-tag {
  margin: 15px;
}
.input-new-tag {
  width: 100px;
}
</style>
